package com.rssfeed.view;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.rssfeed.adaper.RssAdapter;
import com.rssfeed.database.DBController;
import com.rssfeed.model.RSSFeed;
import com.rssfeed.parser.NewsFeedParser;
import com.rssfeed.utility.Utility;
import com.rssfeed.voa.R;

public class RssListFeedActivity extends Activity implements OnItemClickListener {

    private ListView mRssListView;
    private RSSFeed mRssFeed;
    private NewsFeedParser mNewsFeeder;
    private List<RSSFeed> mRssFeedList;
    private RssAdapter mRssAdap;
    private DBController dbc;
    private LinearLayout emptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rss_feed_view);

        mRssListView = (ListView) findViewById(R.id.rss_list_view);
        mRssFeedList = new ArrayList<RSSFeed>();
        emptyView = (LinearLayout) findViewById(R.id.emptyView);
        
        new DoRssFeedTask(this).execute(Utility.url);
        dbc = new DBController(this);
    
        mRssListView.setOnItemClickListener(this);
    }

    public class DoRssFeedTask extends AsyncTask<String, Void, Void> {
        ProgressDialog prog;
        String jsonStr = null;
        Handler innerHandler;
        Context mContext;
        
        public DoRssFeedTask(Context context) {
        	mContext = context;
        }
        
        @Override
        protected void onPreExecute() {
            prog = new ProgressDialog(mContext);
            prog.setMessage("Loading....");
            prog.show();
        }

        @Override
        protected Void doInBackground(String... params) {
            for (String urlVal : params) {
                mNewsFeeder = new NewsFeedParser(urlVal);
            }
            mRssFeedList = mNewsFeeder.parse();
            //Log.d("tag", "=" + String.valueOf(mRssFeedList.size()));
            if (mRssFeedList!= null && mRssFeedList.size() > 0) {
            	 Log.d("Thinhdt", "mRssFeedList size: " + mRssFeedList.size());
            	 Log.d("Thinhdt", "mRssFeedList size: " + mRssFeedList.get(0).getLink());
            }
			return null;
        }
        

        @Override
        protected void onPostExecute(Void result) {
//        	 int count = mRssAdap.getCount();
//        	 Log.d("Thinhdt", "mRssFeedList size count: " + count);
           
        	if (mRssFeedList!= null && mRssFeedList.size() > 0) {
        		addDatabase(mRssFeedList);
        		mRssAdap = new RssAdapter(RssListFeedActivity.this,
    					R.layout.rss_list_item, mRssFeedList);
    			mRssListView.setAdapter(mRssAdap);
    			mRssAdap.notifyDataSetChanged();
        	}else{
        		mRssFeedList = getDataFromDatabase();
        		if(mRssFeedList.size()>0){
        			mRssAdap = new RssAdapter(RssListFeedActivity.this,
        					R.layout.rss_list_item, mRssFeedList);
        			mRssListView.setAdapter(mRssAdap);
        			mRssAdap.notifyDataSetChanged();
        		}else {
        			emptyView.setVisibility(View.VISIBLE);
        			Toast.makeText(getBaseContext(), "Data null", Toast.LENGTH_SHORT).show();   
        		}
        	}
            
            if (prog != null) {
            	prog.dismiss();
            }
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
    	mRssFeed = mRssFeedList.get(position);
    	Intent i = new Intent(RssListFeedActivity.this, RssDetailsActitvity.class);
		i.putExtra("RssFeedStructure", mRssFeed);
		startActivity(i);
    }
    
    /**
     * 
     * @param List<RssFeed>
     */
    public void addDatabase(List<RSSFeed> result){
    	for (int i = 0; i < result.size(); i++) {
			if(!dbc.checkID(result.get(i).getFeedId())){
				dbc.addData(result.get(i).getFeedId(), 
								result.get(i).getTitle(), 
						        result.get(i).getDescription(), 
						        result.get(i).getLink(),
						        result.get(i).getPubDate(), 
						        result.get(i).getImgLink(), 
						        result.get(i).getMp3Link());
			}	
		}
    }
    /**
     * 
     * @date 23-05
     * @return List<RssFeed> load from database
     */
    public List<RSSFeed> getDataFromDatabase(){
    	dbc = new DBController(this);
    	dbc.open();
    	List<RSSFeed> result = dbc.getdata();
    	dbc.close();
    	return result;
    }
}
